#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>

#include "main.h"
#include "daemon.h"


/* modified source from: http://blog.abhijeetr.com/2010/03/writing-daemon-in-c-or-daemonize.html */
int
daemonize(void)
{
  int devfd;
  /* Our process ID and Session ID */
  pid_t pid, sid;

  I2("forking into the background")
  /* check write access to /dev/null */
  if (access("/dev/null", W_OK) != 0)
  {
    W2_errstr("/dev/null not accessable")
    return (1);
  }

  /* fork off the parent process */
  pid = fork();
  /* fork error */
  if (pid < 0) {
    exit(1);
  }

  /* If we got a good PID, then we can exit the parent process. */
  if (pid > 0) {
    /* parent process should exit */
    return (-1);
  }

  /* Change the file mode mask */
  umask(0);

  /* Create a new SID for the child process */
  sid = setsid();
  if (sid < 0) {
    exit(1);
  }

  /* Change the current working directory */
  if ((chdir("/")) < 0) {
    /* Log the failure */
    exit(1);
  }

  /* Close out the standard file descriptors */
  devfd = open("/dev/null", O_RDONLY | O_WRONLY);
  if (devfd < 0)
  {
    E2("/dev/null does not exist or is not read-/write-able");
    exit(1);
  }
  DD2("closing stdin");
  close(STDIN_FILENO);
  dup2(devfd, STDIN_FILENO);
  close(devfd);

  /* change proc name */
#if defined(PACKAGE_NAME) && defined(HAVE_PRCTL)
  prctl(PR_SET_NAME, (unsigned long) PACKAGE_NAME, 0,0,0);
#endif

  return (0);
}

